package com.sz.biz.app.web.api.system;

import com.sz.common.base.dao.Dao;
import com.sz.common.base.dto.ResultDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

/**
 * Function: TODO: ADD FUNCTION <br>
 * Author: Charles. <br>
 * Date: 2017-03-13 14:20:00.
 */
@RestController
@RequestMapping("/api/v1/sys/time")
@Api(description = " ", tags = "101、时间管理")
public class TimeController {

    @Autowired
    Dao dao;

    @ApiOperation(value = "获取系统时间", notes = "-")
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public ResultDto getDbTime(@RequestParam(required = false, defaultValue = "yyyy-MM-dd HH:mm:ss") String fmt,
                               @RequestParam(required = false, defaultValue = "Asia/Shanghai") String timezone) {
        try {
            String timeString = "1970-01-01 00:00:00";
            Timestamp time = this.dao.getDbDate();
            Date date = new Date(time.getTime());
            int offset = Calendar.getInstance().getTimeZone().getOffset(time.getTime());
            if (offset != 28800000) { //java VM 时区不在UTC+8时区
                /**
                 * Mysql数据库的时区设置为UTC+8:00,
                 * getDbDate返回当前时间与1970-01-01 00:00:00 UTC+8 的毫秒数，
                 * 而不是与1970-01-01 00:00:00 UTC的毫秒数
                 */
                long utcTime = time.getTime() - 28800000;
                /**
                 * Java VM 在时区转换时默认以系统当前时区为源时区，所以把时间转换到系统当前时区
                 */
                date = new Date(utcTime + offset);
            }
            if (StringUtils.hasLength(fmt)) { //格式转换
                SimpleDateFormat outputFormat = new SimpleDateFormat(fmt);
                if (StringUtils.hasLength(timezone)) {
                    TimeZone tz = TimeZone.getTimeZone(timezone);
                    outputFormat.setTimeZone(tz);
                }
                timeString = outputFormat.format(date);
            }
            ResultDto dto = new ResultDto(timeString);
            return dto;
        } catch (Exception ex) {
            ResultDto dto = new ResultDto(-1, ex.toString());
            return dto;
        }
    }
}
